<template>
    <div>
        <el-dialog v-model="props.shopProductOpen" :title="title" width="650" @close="handleShopProductClose">

            <el-form ref="shopProductRef" :model="form" :rules="rulesShopProduct" label-width="auto"
                label-position="left">
                <el-form-item label="上级ID" prop="parentId" required>
                    <el-tree-select v-model="form.parentId" :data="tableData" :props="treeProps" value-key="id"
                        placeholder="请选择上级ID" check-strictly filterable :disabled="true" />
                </el-form-item>
                <el-form-item label="来源网站" prop="collectionSiteId">
                    <el-select v-model="form.collectionSiteId" placeholder="请选择" disabled>
                        <el-option v-for="dict in props.host_type" :key="dict.di" :label="dict.name"
                            :value="dict.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="添加语言" prop="languageIds" required>
                    <el-select v-model="form.languageIds" placeholder="请选择" filterable multiple collapse-tags
                        @change="changeLanguageId">
                        <el-option v-for="dict in sys_language_type" :key="dict.id" :label="dict.description"
                            :value="dict.id" :disabled="dict?.disabled">
                            <!--  根据条件控制是否显示删除按钮 -->
                        </el-option>
                        <template #tag>
                            <el-tag v-for="code in form.descriptions" :key="code" type="info">
                                {{ code.languageIdName }}
                            </el-tag>
                        </template>
                    </el-select>
                </el-form-item>
                <el-tabs v-model="activeName" type="card" style="width: 100%;">
                    <el-tab-pane v-for="item in form.descriptions" :key="item.name" :name="item.languageId">
                        <template #label>
                            {{ item.languageIdName }}
                            <el-icon style="margin-left: 10px;" v-if="item.languageId != publicDetails.languageId"
                                @click="removeTab(item.languageId)">
                                <CircleCloseFilled />
                            </el-icon>
                        </template>
                    </el-tab-pane>
                </el-tabs>
                <div v-for="item in form.descriptions" :key="item.languageId">
                    <div v-show="activeName === item.languageId">
                        <el-form-item label="分类名称" prop="name">
                            <el-input v-model.trim="item.name" maxlength="100" show-word-limit type="textarea"
                                :rows="3"  resize="none"/>
                        </el-form-item>
                        <el-form-item label="SEO标题" prop="seoTitle">
                            <el-input v-model.trim="item.seoTitle" maxlength="500" show-word-limit type="textarea" :rows="3"/>
                        </el-form-item> <el-form-item label="SEO描述" prop="seoDescription">
                            <el-input v-model.trim="item.seoDescription" maxlength="500" show-word-limit
                                type="textarea" :rows="4"/>
                        </el-form-item>
                        <el-form-item label="SEO标签" prop="seoKeywords">
                            <el-input v-model.trim="item.seoKeywords" maxlength="500" show-word-limit type="textarea" :rows="3"/>
                        </el-form-item> <el-form-item label="描述" prop="description">
                            <el-input v-model.trim="item.description" maxlength="500" show-word-limit type="textarea" :rows="3"/>
                        </el-form-item>
                    </div>
                </div>
            </el-form>

            <template #footer>
                <el-button @click="handleShopProductClose">取消</el-button>
                <el-button type="primary" @click="handleShopProductSure">
                    确认
                </el-button>
            </template>

        </el-dialog>
    </div>
</template>
<script setup>
import { CircleCloseFilled } from '@element-plus/icons-vue'
import { ref, defineProps, defineEmits, watch, reactive, onMounted } from "vue";
const { proxy } = getCurrentInstance();
const emits = defineEmits(["handleShopProductClose", "handleShopProductSure"]);
const sys_language_type = ref([])
const tableData = ref([])
const title = ref('')
const activeName = ref(1)
const publicDetails = ref({})//详情数据
const form = ref({
    collectionSiteId: null,//采集站点ID
    parentId: null,//父类别ID 没有可不传
    languageIds: [],//选择的语言列表数据
    descriptions: [
        // name:'',//分类名称
        // seoTitle：'',//SEO标题
        // seoDescription:'',//SEO描述
        // seoKeywords:'',//seo描述
        // description:''//描述
    ]//多语言
})
const searchFrom = ref({// 查询参数
    pageNum: 1,
    pageSize: 999,
    param: {
    },
});
const props = defineProps({
    shopProductOpen: {
        type: Boolean,
        default: false,
    },
    publicItem: {
        type: Object,
        default: {},
    },
    newType: {
        type: Number,
        default: 3//1是编辑2是新增里面的3是新增外面的
    },
    host_type: {
        type: Array,
        default: [],
    }
});
watch(
    () => props.shopProductOpen,
    () => {
        if (!props.shopProductOpen) return
        getProcessing()
        // getList()
    })
const handleShopProductSure = () => {
    proxy.$refs["shopProductRef"].validate((valid) => {
        if (!valid) return
        if (!proxy.publicArray(form.value.descriptions)) return proxy.$modal.msgError("请完整填写分类名称")
        product.rawcategory.rawcategoryUpdatedescription(
            {
                pathParams: {
                    id: props.publicItem.id
                },
                data: form.value
            }
        ).then((res) => {
            if (res.code === 200) {
                processingClose()
                proxy.$modal.msgSuccess(res.message);
                emits("handleShopProductSure")
            }
        })
        console.log(form.value, '[[[[]]]]');
    })
}

// 处理逻辑watch
const getProcessing = () => {
    console.log(props.newType);
    if (props.newType === 1) {
        title.value = '编辑'
        getDetails()
    } else if (props.newType === 2) {
        title.value = '新增'
        getDetails()
    } else {
        form.value.parentId = 0
        title.value = '新增'
    }
}

const getList = (parentId) => {//获取上一页列表数据=====上级节点列表数据
    product.rawcategory.rawcategoryList({
        data: {
            pageNum: 1,
            pageSize: 999,
            param: {
                ids: [parentId],
            },
        }
    }).then((res) => {
        if (res.code === 200) {
            tableData.value = []
            const data = { id: 0, name: "顶级节点", children: [] };
            tableData.value = res.data
            tableData.value.unshift(data);
        }
    })
}
// 获取详情数据
const getDetails = () => {//获取详情数据
    product.rawcategory.rawcategoryGetbyid({
        pathParams: {
            id: props.publicItem.id
        }
    }).then((res) => {
        if (res.code === 200) {
            getList(res.data.parentId)//获取上级ID
            choseWebSite(res.data.languageId)//限制语言某一条数据，不能被选择取消
            activeName.value = res.data.languageId
            publicDetails.value = res.data
            form.value.parentId = res.data.parentId
            form.value.collectionSiteId = res.data.collectionSiteId
            form.value.languageIds = []
            form.value.languageIds.push(res.data.languageId)
            if (res.data.descriptions) {
                res.data.descriptions.forEach((e) => {
                    form.value.descriptions.push({
                        languageId: e.languageId,
                        languageIdName: sys_language_type.value.find(code => code.id === e.languageId)?.description,
                        name: e.name,//分类名称
                        seoTitle: e.seoTitle,//SEO标题
                        seoDescription:proxy.decodeHtmlEntities( e.seoDescription),//SEO描述
                        seoKeywords: e.seoKeywords,//seo标签
                        description: proxy.decodeHtmlEntities(e.description)//描述
                    })
                })
            } else {
                form.value.descriptions.push({
                    languageId: res.data.languageId,
                    languageIdName: sys_language_type.value.find(e => e.id === res.data.languageId)?.description,
                    name: '',//分类名称
                    seoTitle: '',//SEO标题
                    seoDescription: '',//SEO描述
                    seoKeywords: '',//seo标签
                    description: ''//描述
                })
            }
        }
        console.log(res.data);
    })

}
// 选择来源网站把默认语言取出来
const choseWebSite = (languageId) => {
    let existLanguage = sys_language_type.value.find(e => e.id === languageId)
    if (existLanguage) {
        sys_language_type.value.find(e => e.id === languageId).disabled = true
    }
}
onMounted(() => {
    getLanguage()//获取语言
})
const getLanguage = () => {//语言列表数据
    product.language.languageList().then((res) => {
        sys_language_type.value = res.data;
    });
}

// 自定义 props
const treeProps = {
    label: "name",
    value: "id",
    children: "children",
};
const rulesShopProduct = reactive({
    parentId: [
        { required: true, message: "请选择上级ID", trigger: "blur" },
    ],
    languageIds: [{ required: true, message: "请选择", trigger: "blur" }],
})
const changeLanguageId = (e) => {
    console.log(e, '[[[[]]]]');
    processingLanguageId(e)
    // console.log(sys_language_type.value);
}
const removeTab = (e) => {
    form.value.languageIds = form.value.languageIds.filter(item => item !== e);
    form.value.descriptions = form.value.descriptions.filter(item => item.languageId !== e);
}
// 设定某些选项不可删除
const processingLanguageId = (list) => {
    list.forEach(id => {
        const exists = form.value.descriptions.findIndex(item => item.languageId === id);
        if (exists === -1) {
            form.value.descriptions.push({
                languageId: id,
                languageIdName: sys_language_type.value.find(e => e.id === id)?.description,
                name: '',
                seoTitle: '',
                seoDescription: '',
                seoKeywords: '',
                description: ''
            });
        }
    })
};

const handleShopProductClose = () => {
    processingClose()
    emits("handleShopProductClose")
}
const processingClose = () => {
    proxy.resetForm("shopProductRef");
    form.value = {
        parentId: null,
        languageIds: [],
        descriptions: []
    }
    sys_language_type.value.forEach(item => {
        item.disabled = false;
    });
}
</script>